<!-- Cart.vue - 购物车页面 -->
<template>
  <div class="cart-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <el-icon class="header-icon"><ShoppingCart /></el-icon>
      <h2 class="header-title">我的购物车</h2>
      <p class="header-subtitle">{{ cartList.length }} 件商品</p>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton v-for="i in 3" :key="i" :rows="2" animated class="loading-item" />
    </div>

    <!-- 空购物车 -->
    <div v-else-if="cartList.length === 0" class="empty-cart">
      <el-empty description="购物车空空如也">
        <el-icon class="empty-icon" :size="120" color="#909399"><ShoppingCartFull /></el-icon>
        <template #description>
          <p class="empty-text">购物车空空如也，快去逛逛吧</p>
        </template>
        <el-button type="primary" @click="goToMarket" size="large">
          去渔具市场逛逛
        </el-button>
      </el-empty>
    </div>

    <!-- 购物车列表 -->
    <div v-else class="cart-content">
      <!-- 操作栏 -->
      <div class="cart-toolbar">
        <el-checkbox v-model="isAllSelected" @change="handleSelectAll">
          全选
        </el-checkbox>
        <div class="toolbar-actions">
          <el-button text @click="handleBatchDelete" :disabled="selectedIds.length === 0">
            <el-icon><Delete /></el-icon>
            删除选中 ({{ selectedIds.length }})
          </el-button>
        </div>
      </div>

      <!-- 商品列表 -->
      <div class="cart-list">
        <el-card 
          v-for="item in cartList" 
          :key="item.cartId" 
          class="cart-item"
          :class="{ 'is-selected': item.isSelected }"
          shadow="hover"
        >
          <div class="item-content">
            <!-- 选择框 -->
            <el-checkbox 
              v-model="item.isSelected" 
              @change="handleSelectItem(item)"
              class="item-checkbox"
            />

            <!-- 商品图片 -->
            <div class="item-image" @click="viewProduct(item.productId)">
              <el-image 
                :src="item.coverList && item.coverList[0] ? item.coverList[0] : ''" 
                fit="cover"
                class="product-image"
              >
                <template #error>
                  <div class="image-error">
                    <el-icon><PictureFilled /></el-icon>
                    <div style="font-size: 10px; margin-top: 2px;">
                      {{ item.coverList ? `原始: ${item.coverList}` : '无图片数据' }}
                    </div>
                  </div>
                </template>
              </el-image>
            </div>

            <!-- 商品信息 -->
            <div class="item-info">
              <h3 class="product-name" @click="viewProduct(item.productId)">
                {{ item.productName }}
              </h3>
              <div class="product-tags">
                <el-tag :type="getOldLevelType(item.oldLevel)" size="small">
                  {{ getOldLevelText(item.oldLevel) }}
                </el-tag>
              </div>
              <div class="product-price">
                <span class="price-symbol">¥</span>
                <span class="price-value">{{ item.price }}</span>
              </div>
            </div>

            <!-- 数量显示（二手商品固定为1） -->
            <div class="item-quantity">
              <div class="quantity-display">
                <span class="quantity-label">数量：</span>
                <span class="quantity-value">1</span>
                <span class="quantity-note">（二手商品）</span>
              </div>
            </div>

            <!-- 小计 -->
            <div class="item-subtotal">
              <p class="subtotal-label">小计</p>
              <p class="subtotal-value">¥{{ item.price.toFixed(2) }}</p>
            </div>

            <!-- 删除按钮 -->
            <el-button 
              class="item-delete"
              type="danger"
              text
              @click="handleDelete(item)"
              circle
            >
              <el-icon><Delete /></el-icon>
            </el-button>
          </div>
        </el-card>
      </div>

      <!-- 结算栏 -->
      <div class="checkout-bar">
        <div class="checkout-left">
          <el-checkbox v-model="isAllSelected" @change="handleSelectAll">
            全选
          </el-checkbox>
          <el-button text type="danger" @click="handleBatchDelete" :disabled="selectedIds.length === 0">
            删除选中
          </el-button>
        </div>
        
        <div class="checkout-right">
          <div class="price-info">
            <span class="price-label">
              已选商品 <span class="price-count">{{ selectedIds.length }}</span> 件
            </span>
            <div class="price-detail">
              <span class="price-label">合计：</span>
              <span class="price-symbol">¥</span>
              <span class="price-value">{{ totalPrice }}</span>
            </div>
          </div>
          <el-button 
            type="primary" 
            size="large"
            @click="handleCheckout"
            :disabled="selectedIds.length === 0"
            class="checkout-btn"
          >
            结算 ({{ selectedIds.length }})
          </el-button>
        </div>
      </div>
    </div>

    <!-- 订单确认对话框 -->
    <el-dialog
      v-model="showOrderDialog"
      title="确认订单"
      width="90%"
      :max-width="800"
      :close-on-click-modal="false"
      class="order-dialog"
    >
      <div class="order-dialog-content">
        <!-- 商品信息 -->
        <el-card class="order-section" shadow="never">
          <template #header>
            <div class="section-title">
              <el-icon><Box /></el-icon>
              <span>商品信息</span>
            </div>
          </template>
          
          <div class="selected-products">
            <div 
              v-for="item in selectedItems" 
              :key="item.cartId"
              class="product-item"
            >
              <div class="product-image">
                <el-image 
                  :src="item.coverList[0]" 
                  fit="cover"
                  class="product-img"
                >
                  <template #error>
                    <div class="image-error">
                      <el-icon><PictureFilled /></el-icon>
                    </div>
                  </template>
                </el-image>
              </div>
              
              <div class="product-info">
                <h4 class="product-name">{{ item.productName }}</h4>
                <div class="product-meta">
                  <el-tag :type="getOldLevelType(item.oldLevel)" size="small">
                    {{ getOldLevelText(item.oldLevel) }}
                  </el-tag>
                  <span class="product-price">¥{{ item.price }}</span>
                </div>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 订单信息 -->
        <el-card class="order-section" shadow="never">
          <template #header>
            <div class="section-title">
              <el-icon><Document /></el-icon>
              <span>订单信息</span>
            </div>
          </template>
          
          <el-form
            ref="orderFormRef"
            :model="orderForm"
            :rules="orderRules"
            label-width="100px"
            class="order-form"
          >
            <el-form-item label="购买数量">
              <el-input-number
                v-model="orderForm.quantity"
                :min="1"
                :max="1"
                :disabled="true"
                controls-position="right"
              />
              <span class="form-tip">二手商品数量固定为1</span>
            </el-form-item>

            <el-form-item label="收货人" prop="buyerName">
              <el-input
                v-model="orderForm.buyerName"
                placeholder="请输入收货人姓名"
                maxlength="20"
                show-word-limit
              />
            </el-form-item>

            <el-form-item label="联系电话" prop="buyerPhone">
              <el-input
                v-model="orderForm.buyerPhone"
                placeholder="请输入联系电话"
                maxlength="20"
              />
            </el-form-item>

            <el-form-item label="收货地址" prop="buyerAddress">
              <el-input
                v-model="orderForm.buyerAddress"
                type="textarea"
                :rows="3"
                placeholder="请输入详细的收货地址"
                maxlength="200"
                show-word-limit
              />
            </el-form-item>

            <el-form-item label="订单备注" prop="detail">
              <el-input
                v-model="orderForm.detail"
                type="textarea"
                :rows="2"
                placeholder="选填，如：请尽快发货、包装要求等"
                maxlength="100"
                show-word-limit
              />
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 订单汇总 -->
        <el-card class="order-section" shadow="never">
          <template #header>
            <div class="section-title">
              <el-icon><Money /></el-icon>
              <span>订单汇总</span>
            </div>
          </template>
          
          <div class="order-summary">
            <div class="summary-row">
              <span class="label">商品单价：</span>
              <span class="value">¥{{ totalPrice / selectedItems.length }}</span>
            </div>
            <div class="summary-row">
              <span class="label">购买数量：</span>
              <span class="value">{{ selectedItems.length }}</span>
            </div>
            <div class="summary-row total-row">
              <span class="label">实付款：</span>
              <span class="value total-amount">¥{{ totalPrice.toFixed(2) }}</span>
            </div>
          </div>
        </el-card>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showOrderDialog = false">
            返回修改
          </el-button>
          <el-button 
            type="primary" 
            @click="submitOrder"
            :loading="submitting"
            class="submit-btn"
          >
            <el-icon><CreditCard /></el-icon>
            {{ submitting ? '创建中...' : '确认下单' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { cartAPI, orderAPI, productAPI } from '@/api'
import {
  ShoppingCart,
  ShoppingCartFull,
  Delete,
  PictureFilled,
  Box,
  Document,
  Money,
  CreditCard
} from '@element-plus/icons-vue'

const router = useRouter()

// 响应式数据
const cartList = ref([])
const loading = ref(false)

// 全选状态
const isAllSelected = computed({
  get: () => cartList.value.length > 0 && cartList.value.every(item => item.isSelected),
  set: (value) => {
    cartList.value.forEach(item => item.isSelected = value)
  }
})

// 选中的商品ID列表
const selectedIds = computed(() => {
  return cartList.value.filter(item => item.isSelected).map(item => item.cartId)
})

// 总价
const totalPrice = computed(() => {
  return cartList.value
    .filter(item => item.isSelected)
    .reduce((sum, item) => sum + item.price, 0)
})

// 选中的商品列表
const selectedItems = computed(() => {
  return cartList.value.filter(item => item.isSelected)
})

// 订单相关数据
const showOrderDialog = ref(false)
const submitting = ref(false)
const orderFormRef = ref(null)
const orderForm = ref({
  quantity: 1,
  buyerName: '',
  buyerPhone: '',
  buyerAddress: '',
  detail: ''
})

// 订单表单验证规则
const orderRules = {
  buyerName: [
    { required: true, message: '请输入收货人姓名', trigger: 'blur' }
  ],
  buyerPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  buyerAddress: [
    { required: true, message: '请输入收货地址', trigger: 'blur' }
  ]
}

// 获取购物车列表
const fetchCartList = async () => {
  try {
    loading.value = true
    const response = await cartAPI.getCartList()
    
    if (response.code === 0 && Array.isArray(response.data)) {
      cartList.value = response.data.map(item => {
        console.log('购物车页面原始coverList:', item.coverList, '类型:', typeof item.coverList)
        const parsedCoverList = parseCoverList(item.coverList)
        console.log('购物车页面解析后coverList:', parsedCoverList)
        return {
          ...item,
          isSelected: item.isSelected === 1 || item.isSelected === true,
          coverList: parsedCoverList // 预处理coverList
        }
      })
    }
  } catch (error) {
    console.error('获取购物车失败:', error)
    ElMessage.error('获取购物车失败')
  } finally {
    loading.value = false
  }
}

// 全选/取消全选
const handleSelectAll = async (value) => {
  try {
    await cartAPI.selectAll(value)
    ElMessage.success(value ? '已全选' : '已取消全选')
  } catch (error) {
    console.error('全选操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 选中单个商品
const handleSelectItem = async (item) => {
  try {
    await cartAPI.toggleSelect(item.cartId, item.isSelected)
  } catch (error) {
    console.error('选中失败:', error)
    item.isSelected = !item.isSelected
  }
}

// 删除单个商品
const handleDelete = async (item) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除【${item.productName}】吗？`,
      '删除商品',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await cartAPI.deleteCart(item.cartId)
    ElMessage.success('删除成功')
    cartList.value = cartList.value.filter(i => i.cartId !== item.cartId)
    
    // 触发全局事件，通知其他页面更新购物车状态
    window.dispatchEvent(new CustomEvent('cartItemDeleted', {
      detail: { productId: item.productId }
    }))
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请先选择要删除的商品')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedIds.value.length} 件商品吗？`,
      '批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await cartAPI.batchDelete(selectedIds.value)
    ElMessage.success('删除成功')
    
    // 获取被删除的商品ID列表，用于触发全局事件
    const deletedProductIds = cartList.value
      .filter(item => selectedIds.value.includes(item.cartId))
      .map(item => item.productId)
    
    cartList.value = cartList.value.filter(item => !selectedIds.value.includes(item.cartId))
    
    // 触发全局事件，通知其他页面更新购物车状态
    deletedProductIds.forEach(productId => {
      window.dispatchEvent(new CustomEvent('cartItemDeleted', {
        detail: { productId }
      }))
    })
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 结算
const handleCheckout = () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请先选择要结算的商品')
    return
  }
  
  // 显示订单确认对话框
  showOrderDialog.value = true
}

// 查看商品详情
const viewProduct = (productId) => {
  router.push(`/gear/product/${productId}`)
}

// 提交订单
const submitOrder = async () => {
  try {
    // 验证表单
    await orderFormRef.value.validate()
    
    // 确认对话框
    await ElMessageBox.confirm(
      `确认购买 ${selectedItems.value.length} 件商品，总金额 ¥${totalPrice.value.toFixed(2)}？`,
      '确认下单',
      {
        confirmButtonText: '确认下单',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    submitting.value = true
    
    // 为每个选中的商品创建订单
    const orderPromises = selectedItems.value.map(item => {
      return orderAPI.createOrder({
        productId: item.productId,
        quantity: 1,
        buyerName: orderForm.value.buyerName,
        buyerPhone: orderForm.value.buyerPhone,
        buyerAddress: orderForm.value.buyerAddress,
        detail: orderForm.value.detail
      })
    })
    
    const results = await Promise.all(orderPromises)
    
    // 检查所有订单是否创建成功
    const successCount = results.filter(result => result.code === 0).length
    
    if (successCount === selectedItems.value.length) {
      ElMessage.success(`成功创建 ${successCount} 个订单`)
      
      // 更新商品状态为已售出
      try {
        const statusUpdatePromises = selectedItems.value.map(item => {
          return productAPI.updateProductStatus(item.productId, 'sold')
        })
        await Promise.all(statusUpdatePromises)
      } catch (error) {
        ElMessage.warning('订单创建成功，但商品状态更新失败，请联系管理员')
      }
      
      // 从购物车中删除已下单的商品
      try {
        const orderedCartIds = selectedItems.value.map(item => item.cartId)
        const deletePromises = orderedCartIds.map(cartId => {
          return cartAPI.deleteCart(cartId)
        })
        await Promise.all(deletePromises)
      } catch (error) {
        ElMessage.warning('订单创建成功，但购物车清理失败，请手动删除')
      }
      
      // 关闭对话框并刷新购物车
      showOrderDialog.value = false
      
      // 重置表单，不阻塞主流程
      try {
        resetOrderForm()
      } catch (error) {
        console.error('重置表单失败:', error)
      }
      
      // 异步刷新购物车，不阻塞主流程
      fetchCartList().catch(error => {
        console.error('刷新购物车失败:', error)
      })
      
      // 触发订单创建事件
      try {
        window.dispatchEvent(new CustomEvent('orderCreated', {
          detail: { 
            orderCount: successCount,
            totalAmount: totalPrice.value
          }
        }))
      } catch (error) {
        console.error('触发订单创建事件失败:', error)
      }
    } else {
      ElMessage.warning(`部分订单创建失败，成功 ${successCount}/${selectedItems.value.length} 个`)
    }
    
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('订单创建失败')
    }
  } finally {
    submitting.value = false
  }
}

// 重置订单表单
const resetOrderForm = () => {
  orderForm.value = {
    quantity: 1,
    buyerName: '',
    buyerPhone: '',
    buyerAddress: '',
    detail: ''
  }
  if (orderFormRef.value) {
    orderFormRef.value.clearValidate()
  }
}

// 去市场
const goToMarket = () => {
  router.push('/gear/market')
}

// 获取图片URL
const getFirstImage = (coverList) => {
  const parsedList = parseCoverList(coverList)
  return parsedList.length > 0 ? parsedList[0] : ''
}

/**
 * 安全解析 coverList 字段
 */
const parseCoverList = (coverList) => {
  // 如果已经是数组，直接返回
  if (Array.isArray(coverList)) {
    return coverList.filter(url => url && !url.startsWith('blob:'))
  }
  
  // 如果是字符串，尝试解析
  if (typeof coverList === 'string') {
    // 如果是空字符串，返回空数组
    if (!coverList.trim()) {
      return []
    }
    
    // 如果看起来像URL（以http开头），包装成数组
    if (coverList.startsWith('http')) {
      // 检查是否包含多个URL（没有分隔符的情况）
      // 修复正则表达式，更精确地匹配URL
      const urlPattern = /https?:\/\/[^,\s]+/g
      const urls = coverList.match(urlPattern)
      if (urls && urls.length > 0) {
        return urls.filter(url => url && !url.startsWith('blob:'))
      }
      return [coverList]
    }
    
    // 尝试解析JSON字符串
    try {
      const parsed = JSON.parse(coverList)
      
      // 处理嵌套的successUrls结构
      if (parsed && typeof parsed === 'object') {
        if (parsed.successUrls && Array.isArray(parsed.successUrls)) {
          return parsed.successUrls.filter(url => url && !url.startsWith('blob:'))
        }
        if (Array.isArray(parsed)) {
          return parsed.filter(url => url && !url.startsWith('blob:'))
        }
      }
      
      return Array.isArray(parsed) ? parsed.filter(url => url && !url.startsWith('blob:')) : []
    } catch (error) {
      return []
    }
  }
  
  // 其他情况返回空数组
  return []
}

// 获取新旧程度文本
const getOldLevelText = (level) => {
  const map = {
    1: '较旧', 2: '旧', 3: '较新', 
    4: '95新', 5: '全新',
    6: '95新', 7: '95新', 8: '较新',
    9: '95新', 10: '全新'
  }
  return map[level] || '未知'
}

// 获取新旧程度类型
const getOldLevelType = (level) => {
  if (level >= 9) return 'success'
  if (level >= 7) return 'info'
  if (level >= 5) return 'warning'
  return 'danger'
}

// 页面加载
onMounted(() => {
  fetchCartList()
  
  // 监听订单创建事件，当有订单创建时刷新购物车列表
  const handleOrderCreated = (event) => {
    const { productId } = event.detail
    console.log('Cart: 检测到订单创建，商品ID:', productId, '刷新购物车列表')
    
    // 立即从本地状态中移除该商品（如果存在）
    if (productId && cartList.value.length > 0) {
      const index = cartList.value.findIndex(item => item.productId === productId)
      if (index !== -1) {
        console.log('Cart: 立即移除已售商品:', productId)
        cartList.value.splice(index, 1)
        // 重新计算总价
        calculateTotal()
      }
    }
    
    // 刷新购物车列表（从后端获取最新数据）
    fetchCartList()
  }
  
  window.addEventListener('orderCreated', handleOrderCreated)
  
  // 保存事件处理器引用，用于清理
  window._cartOrderCreatedHandler = handleOrderCreated
})

onUnmounted(() => {
  // 清理事件监听器
  if (window._cartOrderCreatedHandler) {
    window.removeEventListener('orderCreated', window._cartOrderCreatedHandler)
    delete window._cartOrderCreatedHandler
  }
})
</script>

<style scoped lang="scss">
$primary-color: #409eff;
$danger-color: #f56c6c;
$warning-color: #e6a23c;
$success-color: #67c23a;
$text-primary: #303133;
$text-regular: #606266;
$text-secondary: #909399;
$border-color: #dcdfe6;
$bg-color: #f5f7fa;

.cart-page {
  min-height: 100vh;
  background: $bg-color;
  padding: 20px;
}

.page-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 30px;
  border-radius: 12px;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 15px;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);

  .header-icon {
    font-size: 36px;
  }

  .header-title {
    font-size: 28px;
    margin: 0;
    font-weight: 600;
  }

  .header-subtitle {
    margin: 5px 0 0 auto;
    font-size: 16px;
    opacity: 0.9;
  }
}

.loading-container {
  .loading-item {
    background: white;
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 15px;
  }
}

.empty-cart {
  background: white;
  border-radius: 12px;
  padding: 80px 20px;
  text-align: center;

  .empty-icon {
    margin-bottom: 20px;
    opacity: 0.3;
  }

  .empty-text {
    font-size: 18px;
    color: $text-secondary;
    margin: 20px 0;
  }
}

.cart-content {
  max-width: 1200px;
  margin: 0 auto;
}

.cart-toolbar {
  background: white;
  padding: 15px 20px;
  border-radius: 8px;
  margin-bottom: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.cart-list {
  margin-bottom: 80px;

  .cart-item {
    margin-bottom: 15px;
    border-radius: 8px;
    transition: all 0.3s;

    &.is-selected {
      border-color: $primary-color;
      box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
    }

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }
  }
}

.item-content {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 10px;

  .item-checkbox {
    flex-shrink: 0;
  }

  .item-image {
    width: 100px;
    height: 100px;
    border-radius: 8px;
    overflow: hidden;
    cursor: pointer;
    flex-shrink: 0;

    .product-image {
      width: 100%;
      height: 100%;
    }

    .image-error {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      background: $bg-color;
      color: $text-secondary;
    }
  }

  .item-info {
    flex: 1;
    min-width: 0;

    .product-name {
      font-size: 16px;
      color: $text-primary;
      margin: 0 0 10px 0;
      cursor: pointer;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;

      &:hover {
        color: $primary-color;
      }
    }

    .product-tags {
      margin-bottom: 10px;
    }

    .product-price {
      color: $danger-color;
      font-weight: 600;

      .price-symbol {
        font-size: 14px;
      }

      .price-value {
        font-size: 20px;
      }
    }
  }

  .item-quantity {
    flex-shrink: 0;
    
    .quantity-display {
      display: flex;
      align-items: center;
      gap: 5px;
      padding: 8px 12px;
      background: #f5f7fa;
      border-radius: 6px;
      border: 1px solid #e4e7ed;
      
      .quantity-label {
        font-size: 14px;
        color: #606266;
      }
      
      .quantity-value {
        font-size: 16px;
        font-weight: 600;
        color: #409eff;
      }
      
      .quantity-note {
        font-size: 12px;
        color: #909399;
      }
    }
  }

  .item-subtotal {
    width: 120px;
    text-align: right;
    flex-shrink: 0;

    .subtotal-label {
      font-size: 12px;
      color: $text-secondary;
      margin: 0 0 5px 0;
    }

    .subtotal-value {
      font-size: 18px;
      color: $danger-color;
      font-weight: 600;
      margin: 0;
    }
  }

  .item-delete {
    flex-shrink: 0;
  }
}

.checkout-bar {
  position: fixed;
  bottom: 0;
  left: 220px;
  right: 0;
  background: white;
  padding: 20px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
  z-index: 100;

  .checkout-left {
    display: flex;
    align-items: center;
    gap: 20px;
  }

  .checkout-right {
    display: flex;
    align-items: center;
    gap: 30px;

    .price-info {
      text-align: right;

      .price-label {
        font-size: 14px;
        color: $text-regular;
      }

      .price-count {
        color: $primary-color;
        font-weight: 600;
      }

      .price-detail {
        margin-top: 5px;

        .price-symbol {
          font-size: 16px;
          color: $danger-color;
        }

        .price-value {
          font-size: 28px;
          color: $danger-color;
          font-weight: 700;
        }
      }
    }

    .checkout-btn {
      min-width: 140px;
      height: 50px;
      font-size: 18px;
      font-weight: 600;
    }
  }
}

@media (max-width: 768px) {
  .item-content {
    flex-wrap: wrap;

    .item-quantity,
    .item-subtotal {
      width: 100%;
      text-align: left;
      margin-top: 10px;
    }
  }

  .checkout-bar {
    left: 0;
    flex-direction: column;
    gap: 15px;

    .checkout-right {
      width: 100%;
      justify-content: space-between;
    }
  }
}

// 订单对话框样式
.order-dialog {
  .el-dialog__body {
    padding: 0;
  }
}

.order-dialog-content {
  .order-section {
    margin-bottom: 20px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .section-title {
      display: flex;
      align-items: center;
      gap: 8px;
      font-weight: 600;
      color: #303133;
      
      .el-icon {
        color: #409eff;
      }
    }
  }
  
  .selected-products {
    .product-item {
      display: flex;
      align-items: center;
      gap: 15px;
      padding: 15px;
      border: 1px solid #e4e7ed;
      border-radius: 8px;
      margin-bottom: 10px;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .product-image {
        width: 80px;
        height: 80px;
        border-radius: 6px;
        overflow: hidden;
        flex-shrink: 0;
        
        .product-img {
          width: 100%;
          height: 100%;
        }
        
        .image-error {
          display: flex;
          align-items: center;
          justify-content: center;
          height: 100%;
          background: #f5f7fa;
          color: #c0c4cc;
        }
      }
      
      .product-info {
        flex: 1;
        
        .product-name {
          margin: 0 0 8px 0;
          font-size: 16px;
          font-weight: 600;
          color: #303133;
          line-height: 1.4;
        }
        
        .product-meta {
          display: flex;
          align-items: center;
          gap: 10px;
          
          .product-price {
            font-size: 18px;
            font-weight: 700;
            color: #f56c6c;
          }
        }
      }
    }
  }
  
  .order-form {
    .form-tip {
      margin-left: 10px;
      color: #909399;
      font-size: 12px;
    }
  }
  
  .order-summary {
    .summary-row {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 8px 0;
      border-bottom: 1px solid #f0f0f0;
      
      &:last-child {
        border-bottom: none;
      }
      
      .label {
        color: #606266;
        font-size: 14px;
      }
      
      .value {
        color: #303133;
        font-weight: 600;
      }
      
      &.total-row {
        padding-top: 15px;
        margin-top: 10px;
        border-top: 2px solid #e4e7ed;
        
        .label {
          font-size: 16px;
          font-weight: 600;
        }
        
        .total-amount {
          font-size: 20px;
          color: #f56c6c;
          font-weight: 700;
        }
      }
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 15px;
  
  .submit-btn {
    min-width: 120px;
  }
}
</style>
